<template>
    <el-form ref="loginFormRef" :model="loginForm" status-icon :rules="rules" label-width="120px" class="demo-ruleForm">
        <el-form-item label="账&nbsp;&nbsp;&nbsp;号" prop="username">
            <el-input v-model="loginForm.username" type="text" autocomplete="off" />
        </el-form-item>
        <el-form-item label="密&nbsp;&nbsp;&nbsp;码" prop="checkPass">
            <el-input v-model="loginForm.password" type="password" autocomplete="off" />
        </el-form-item>
        <el-form-item label="验证码" prop="captcha" @keydown.enter="submitForm(loginFormRef)">
            <el-input maxlength="5" v-model="loginForm.captcha" />
            <i v-loading="captchaLoading" v-html="captcha" class="captcha" @click="getCaptcha"></i>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="submitForm(loginFormRef)" class="butlogin">登录</el-button>
        </el-form-item>
    </el-form>
</template>
  
<script setup>
import { reactive, ref, onMounted } from 'vue'
// 引入组合式路由
import { useRouter } from "vue-router"
// 引入用户接口
import * as api from "@/api/users.js"
// 引入userStore
import useUser from "@/store/users.js"
// 引入加载loadding
import { ElLoading } from 'element-plus'
// 使用用户仓库
const userStore = useUser()

// 使用路由
let router = useRouter()
const loginFormRef = ref()
// 用户表单验证
const validateuser = (rule, value, callback) => {
    // value就是对应输入框的值
    // callback 如果我们想让验证不通过,就往callback中传递参数,如果通过就不传递参数
    let reg = /^[a-zA-Z0-9_-]{3,16}$/
    if (reg.test(value)) {
        callback()
    } else {
        callback('用户名必须是4到16位(字母,数字,下划线,减号)')
    }
}
// 密码表单验证
const validatePass = (rule, value, callback) => {
    if (value) {
        callback()
    } else {
        callback('密码不能为空')
    }
}
// 验证码表单验证
const validateCaptcha = (rule, value, callback) => {
    if (value) {
        callback()
    } else {
        callback('验证码不能为空')
    }
}
//表单数据
const loginForm = reactive({
    username: '',
    password: '',
    captcha: '',
})
// 表单验证规则
const rules = reactive({
    username: [{ validator: validateuser, trigger: 'blur' }],
    password: [{ validator: validatePass, trigger: 'blur' }],
    captcha: [{ validator: validateCaptcha, trigger: 'blur' }],
})
// 声明验证码响应式变量
let captcha = ref()
// 声明控制验证码的loading打开和关闭的变量
const captchaLoading = ref(false)
// 封装获取验证码的方法
const getCaptcha = async () => {
    // 控制验证码loading打开
    captchaLoading.value =true
    // 发起请求获取验证码
    try {
        let res = await api.getCaptchaApi()
        captcha.value = res.data.img
        // console.log(res);
        // 关闭验证码loading
        captchaLoading.value =false
    } catch (e) {
        console.log(e);
         // 关闭验证码loading
         captchaLoading.value =false
    }
}
//点击登录触发的逻辑
const submitForm = (formEl) => {
    if (!formEl) { return }
    formEl.validate(async (valid) => {
        if (valid) {
            // 验证通过 
                const loading = ElLoading.service({
                    lock: true,
                    text: '登录中...',
                    background: 'rgba(0, 0, 0, 0.7)',
                })
            try {
                let captcahVerify = await checkCaptcha(loginForm.captcha)
                // 验证码通过之后发起登录请求
                if (captcahVerify) {
                    // 获取登录的结果
                    let res = await api.userLoginApi(loginForm.username, loginForm.password)
                    let { permission, token, userInfo } = res.data
                    // 将token存储到本地
                    sessionStorage.setItem('tk', token)
                    // 将permission和userInfo存储到仓库中
                    userStore.permission.value = permission
                    userStore.userInfo.value = userInfo
                    // 跳转到首页
                    router.push('/')
                }
                // 关闭loadding
                loading.close()

            } catch (e) {
                console.log(e);
                // 关闭loadding
                loading.close()
            }
        } else {
            // 表单验证失败 返回false
            return false
        }
    })
}
// 封装验证验证码的方法
const checkCaptcha = async (captcha) => {
    // 将接收的captcha转换为小写
    typeof captcha === 'string' && captcha.toLowerCase()
    try {
        let res = await api.checkCaptchaApi(captcha)
        return res.data.state
    } catch (e) {
        console.log(e);
        getCaptcha()
        return false
    }
}
onMounted(() => {
    getCaptcha()
})


</script>

<style scoped>
.captcha {
    position: absolute;
    top: -2px;
    right: 80px;
    cursor: pointer;
}

.el-input {
    width: 300px;
    height: 50px;
    margin: 0px 0 10px 0;
}

.butlogin {
    position: relative;
    width: 100px;
    left: 90px;
}

.demo-ruleForm {
    width: 500px;
    height: 300px;
    padding-top: 100px;
    border: 1px solid;
}
</style>
  